home *** CD-ROM | disk | FTP | other *** search
/ HPAVC / HPAVC CD-ROM.iso / TPTUTR0F.ZIP / PASCAL2.TXT < prev    next >
Text File  |  1995-12-12  |  14KB  |  313 lines

  1.                         Turbo Pascal for DOS Tutorial
  2.                      Part 2 -- IF statements and FOR loops.
  3.                              by Glenn Grotzinger
  4.             all parts copyright 1995-96 (c) by Glenn Grotzinger.
  5.  
  6.         Hello again.  This part got in a little late (finals in COBOL
  7. programming).  We'll get started with IF statements and FOR loops after
  8. we get the old business taken care of.  Before, we saw this set of code:
  9.  
  10.     first_number := 3;
  11.     second_number := first_number * 2;
  12.     first_number := second_number - 5;
  13.     result := first_number + second_number;
  14.  
  15. The question was what the value of all the variables would be at the end of
  16. the code.  Let's look.  The first statement is a simple assign statement,
  17. assigning first_number the value of 3.  The second statement assigns second_
  18. number the value of first_number (3) * 2 which is 6.  The third statement
  19. then assigns the first_number the value of second_number (6) - 5 which is
  20. 1.  And then the final statement assigns result to the addition of first and
  21. second number.  So, the values of all the variables would be
  22. first_number := 1; second_number := 6; and result := 7;.
  23.  
  24. The example of a solution of last weeks programming question:
  25.  
  26. program part1;
  27.  
  28.   { This program accompanies part1.  It is a program designed to take 2
  29.     numbers as input from the keyboard and perform an addition,
  30.     multiplication, and subtraction on the number, writing the
  31.     results out to the monitor. }
  32.  
  33.   var
  34.     num1, num2: integer;
  35.  
  36.   begin { part1 }
  37.  
  38.     { take input for the 2 numbers }
  39.     write('Please enter the 1st number: ');
  40.     readln(num1);
  41.     write('Please enter the 2nd number: ');
  42.     readln(num2);
  43.  
  44.     writeln;  { place an empty line }
  45.     writeln('Adding ', num1, ' and ', num2, ' gives ', num1 + num2, '.');
  46.     writeln('Subtracting ', num2, ' from ', num1, ' gives ',
  47.              num1 - num2, '.');
  48.     {It is OK to break a command-line of code line this, as long as you
  49.      don't break it on a literal statement}
  50.     writeln('Multiplying ', num1, ' and ', num2, ' gives ', num1 * num2,
  51.             '.');
  52.  
  53.   end. { part1 }
  54.  
  55. OK.  Let's move on to other topics....
  56.  
  57. Format Codes for Read, Write, Readln, and Writeln
  58. =================================================
  59. For all of these commands, we can use formatting codes to place our output,
  60. or input from any source, or to any source (these are always applicable).
  61. Typically, remember that a monitor in text mode has 80 columns and 25 rows.
  62.  
  63.      writeln('I am centered on the screen.':62);
  64.  
  65. This is a good first example.  What will happen is that writeln will place
  66. the end of this text (the .) on screen position 62 columns relative to where
  67. the write pointer is before this command is executed.  Another example.
  68.  
  69.      write(1 / 3 :8:3);
  70.      write(1 / 4 :8:3);
  71.  
  72. Remember that for the screen placement that write/read will invalidate them
  73. if they are not compliant (your code for that line must be greater than the
  74. actual # of characters in the statement you write/read).  With the example
  75. above, we see that it can be done with any type of variable we can write,
  76. or read that is useful.  Above, I'm using expressions of division to
  77. illustrate a point I mentioned last time about regular non-integer division
  78. using decimals.  We'd get something like 3.3333333333E-01 for the first state-
  79. ment, that is if we didn't use the second :# statement.  Obviously, if we
  80. write a program we want to be understandable, we have to use something to
  81. get regular decimal output (incidentally, the 3.33... stuff is how Pascal
  82. stores real numbers in memory -- as scientific notation.).  So we use the
  83. second statement.  The number is the number of decimal places we want to
  84. use for the number.  So, to use those examples above, with a nice little
  85. counter rule (so we can see what is happening only) would look like this:
  86.  
  87. 0000000001111111
  88. 1234567890123456
  89.    0.333   0.250
  90.  
  91. We see that the first number is kicking in...The last position is the 8th
  92. column from the last write position (if we had writeln'd the first one, they
  93. would be lined up on 2 separate lines).  And the answers are reported for
  94. us in decimal format to the 3rd decimal place.  Just play around with
  95. writing different things with these codes, and you'll get the idea of how
  96. to use these codes when writing or reading something.
  97.  
  98. Quick note
  99. ==========
  100. We use ' marks to enclose statements.  What if we want to write one?  Pascal
  101. recognizes that if you place two of them together inside those ' marks, it
  102. will write the actual ' to the output file.  Also, if you can locate an
  103. ASCII table, you can write ASCII codes (lines and such) to screen like this:
  104.        write(#225);
  105. will write ASCII character 225.  You should be able to locate an ASCII chart
  106. in your DOS manual, or your Pascal references that came with your compiler.
  107.  
  108. IF statements
  109. =============
  110. A lot of times, we need to make decisions on a particular course of action.
  111. IF statements are one of those tools.  If a condition is true, then perform
  112. action is basically the logic behind this statement.  We can also assign an
  113. alternate action for the condition.  We will see with this provisional little
  114. example.
  115.  
  116. program tutorial4;
  117.   var
  118.     first_number, second_number: integer;
  119.   begin
  120.     writeln('Type an integer in, please.');
  121.     readln(first_number);
  122.     writeln('Type another integer in, please.');
  123.     readln(second_number);
  124.     writeln;
  125.     if first_number > second_number then
  126.        writeln(first_number, ' is greater than ', second_number, '.')
  127.     else
  128.        writeln(first_number, ' is not greater than ', second_number, '.');
  129.   end.
  130.  
  131. Basically, we made a decision based on the size of the two numbers and
  132. wrote the result of that decision.  Note the format of the test statement.
  133. You can use any of the symbols you remember to relate things together.
  134.                 Not equals is <> in pascal.
  135.                 Greater than or equal to is >= in pascal.
  136.                 Less than or equal to is <= in pascal.
  137.  
  138.         This type also introduces a new type of variable called boolean.
  139. It can only have two values: true, and false.  This type is often good to
  140. test conditions of run-time, such as you see with a lot of programs out
  141. there which can be configured.  IF statements can be used with boolean
  142. variables easily as well.
  143.         Begin and end (end with a ; after it) can also be used in if-else
  144. statements to execute MORE than one line of code if the condition is met,
  145. or not met.  We use the next example.  We also use a multiple-choice
  146. option for function.  We see also a way (not a good one, since there will
  147. be better methods we will cover later.), to allow a catch-all system.
  148. This is also an illustration of something we can most definitely do, is
  149. nest if-else statements.
  150.  
  151. program tutorial5;
  152.   var
  153.     one, two: integer;
  154.     option: char;
  155.   begin
  156.     writeln('Enter an integer.');
  157.     readln(one);
  158.     writeln('Enter another integer.');
  159.     readln(two);
  160.     writeln('Use a mathematical symbol to indicate what you want to do');
  161.     writeln('with these two numbers.');
  162.     readln(option);
  163.     if option = '+' then
  164.        begin
  165.          writeln(one, ' + ', two, ' = ', one + two, '.');
  166.          writeln('See, I can add.');
  167.        end
  168.     else
  169.        if option = '-' then
  170.           writeln(one, ' - ', two, ' = ', one - two, '.')
  171.        else
  172.           if option = '*' then
  173.               writeln(one, ' * ', two, ' = ', one * two, '.')
  174.           else
  175.               if option = '/' then
  176.                   writeln(one, ' / ', two, ' = ', one / two :0:3, '.')
  177.              { we want to have the decimal point, so we MUST have the
  178.                first one as well to be set to 0. }
  179.               else
  180.                 writeln('Use +, -, *, or / as your operator.  Try again.');
  181.   end.
  182.  
  183. We can do pretty much as many nested ifs as we can, though we need to mini-
  184. mize it as much as possible.  Also, keep in mind, we can use AND or OR to
  185. multiply conditions.  Say, on the division, if we wanted to only honor a
  186. division if the first number was greater than the second number  For that
  187. section of code...
  188.  
  189.       if (option = '/') and (one > two) then
  190.       ...
  191.  
  192. Code that's applicant to the IF statement above will execute ONLY when both
  193. conditions are true.  If there are problems that come up in a program using
  194. this, keep in mind the {$B+} compiler directive.  Compiler directives are
  195. placed above the program; part of the program.  Type it as I typed it in the
  196. illustration.  What this does is make it evaluate all the statements of what
  197. I showed above.  Default for Pascal w/o this directive is short-circuit
  198. evaluation.  If option is not / in the above statement, it will not bother to look at the
  199. one > two part of it.  This won't hurt the statement I made above, but it
  200. may for others.  It's something to experiment with...there are no set rules
  201. on when to use the {$B+}.
  202.  
  203. FOR loops
  204. =========
  205. This is a means to repetively execute commands a SET number of times.
  206. They are implemented by an index variable, generally, an integer, but
  207. can also be a character.  THE INDEX VARIABLE VALUE IS NOT ADDRESSABLE
  208. OUTSIDE A FOR LOOP!  Always remember that, though one of those index
  209. variables may be used as a "clean slate" variable for other things.
  210. Examples of FOR loops are...
  211.  
  212.       for i := 1 to 7 do
  213.       { starts at 1, counts to 7, stepping/adding by 1 each execution }
  214.          ...
  215.       for letter := 'a' to 'z' do
  216.       { starts at a, counts through the alphabet, stepping to z by 1 letter }
  217.  
  218.       for i := 10 downto 1 do
  219.       { starts at 10, counts down to 1, stepping/subtracting by 1 }
  220.  
  221. For this short example, keep in mind that the index variables CAN be
  222. addressed inside of the for loop for the values we want....  For counter
  223. variables, it's generally OK to use some letter like i or j or whatever...
  224. Do make your variables DESCRIPTIVE, though.  That's a good programming
  225. practice...
  226.  
  227. program tutorial6;
  228.   var
  229.     i: integer;
  230.   begin
  231.     writeln('I''m going to write something 10 times.');
  232.     for i := 1 to 10 do
  233.       writeln('something', '(Time #':15, i, ')');
  234.   end.
  235.  
  236. Type this one in and run it, and you'll see what it does.  It writes the
  237. first statement above, then writes...
  238.  
  239.    something         (Time #1)
  240.    something         (Time #2)
  241.    ...
  242.    something         (Time #10)
  243.  
  244. We can see a good, real use for this, and keep in mind that groups of
  245. statements can be executed in a for loop, just like if statements by
  246. using begin and end; operators, and for loops can be nested as well...
  247.  
  248. Practice Programming Problem Notes
  249. =====================================
  250. Have people been able to do them adequately?  Please tell me.  Always be
  251. sure to type the examples I give out to see how they work.  Experimentation
  252. and doing the practice programming problems are the best things you can do
  253. to learn by using this tutorial.  Remember, also, to print each of these
  254. parts out as reference for later parts.  Make as a goal for the problems I
  255. present at the end to follow all the guidelines, and try to make them as
  256. SHORT as possible in # of lines of code.  Also, someone suggested a mailing
  257. list to continue this.  If someone would tell me how to set it up (hint,
  258. hint), we may go to that.  Any comments, questions, requests to look at
  259. practice problem code, may be sent to ggrotz@2sprint.net.  Always keep in
  260. mind that there are many different solutions possible to one problem, and
  261. don't be upset if your program didn't look EXACTLY like mine.  If the
  262. output is ACCURATE and your output looks exactly like mine, then your program
  263. is good, and correct.
  264.  
  265. Practice Programming Problem #2
  266. ===============================
  267.         Create a program in Pascal and entirely Pascal that will query the
  268. user for a dimension number to be entered from the keyboard which can not
  269. be greater than 15 (write an error message if it is), and then write out
  270. a multiplication table with the dimension given by the user, with 3 column
  271. spaces between each digit and the double-line (you must use the formatting
  272. codes to accomplish this) to the screen.  Your program must calculate
  273. everything, and nothing can be hard-coded (for example:
  274. write('1   2   3   4   5   6') or something like that).
  275.  
  276. Example output for this program after execution should be something
  277. like this on your screen (if you see garbage around the lookup columns,
  278. those are continuous double lines <ASCII codes>):
  279. --------------------------------------------------------------------------
  280. What dimension number do you want for a table? 4
  281.  
  282.      1   2   3   4
  283.   ╔════════════════
  284.  1║  1   2   3   4
  285.  2║  2   4   6   8
  286.  3║  3   6   9  12
  287.  4║  4   8  12  16
  288.  
  289. Note how I have the numbers lined up in the table.  Your program should do
  290. this as well.  If a dimension is greater than 9, your program should allow
  291. for it by lining up the row counters like you have the answer columns.
  292. Treat what you see above for the table literally (the left side of the file
  293. as the left side of the screen) For example:
  294.  
  295.  9
  296. 10
  297.  
  298. Good luck, and a solution to this problem will appear in part 3!  Remember
  299. to document your code (sort of like I did with the part 1 answer), and try
  300. to keep it short.  The shorter program is the better program, of two programs
  301. that give correct output.  On this one, cosmetics are tedious, but to get
  302. the job done remember that FOR loops are for things that repeat a set number
  303. of times (if you want a goal for practice on getting this one the least
  304. number of lines possible, my solution for this problem is 50 lines long for
  305. code.)
  306.  
  307. Next Time
  308. =========
  309. Next time, we will discuss the use of while and repeat loops, and the
  310. case statement.  By all means, send comments, and queries on problems
  311. you may be encountering with problems in this tutorial to ggrotz@2sprint.net.
  312.  
  313.